package com.zhihuichongcheng.application.ui.im.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMGroup;
import com.hyphenate.exceptions.HyphenateException;
import com.smartlib.cmnObject.recycleView.OnItemOnclick;
import com.smartlib.cmnObject.util.DialogUtil;
import com.smartlib.cmnObject.util.GsonUtil;
import com.smartlib.cmnObject.util.ToastOpt;
import com.zhihuichongcheng.application.R;
import com.zhihuichongcheng.application.base.BaseActivity;
import com.zhihuichongcheng.application.bean.mine.DepInfo;
import com.zhihuichongcheng.application.bean.mine.GroupContactBean;
import com.zhihuichongcheng.application.bean.mine.UserBean;
import com.zhihuichongcheng.application.constant.NetworkAPI;
import com.zhihuichongcheng.application.glide.GlideCircleTransform;
import com.zhihuichongcheng.application.net.HttpCallback;
import com.zhihuichongcheng.application.ui.im.adapter.ContactAdapter;
import com.zhihuichongcheng.application.ui.im.adapter.ExpListAdapter;
import com.zhihuichongcheng.application.widget.CustomExpandableListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 3water on 2016/10/27.
 */

public class ImContactActivity extends BaseActivity implements View.OnClickListener {
    protected List<UserBean> contactList = new ArrayList<>();
    private RecyclerView mRcvContact;
    private TextView mTvSearch;
    private CustomExpandableListView mElvContact;
    private ContactAdapter mAdapter = null;
    private RelativeLayout mRlGroup = null;
    private TextView mTvGroupNum;
    private UserBean mUser = null;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        initView();
        initData();
    }

    private void initView() {
        ImageView avatar = (ImageView) findViewById(R.id.im_avatar);
        Glide.with(mContext).load(R.drawable.ic_chat_group_defalut).transform(new GlideCircleTransform(mContext)).into(avatar);
        mTvGroupNum = (TextView) findViewById(R.id.tv_group_num);
        setTitle("通讯录");
        mElvContact = (CustomExpandableListView) findViewById(R.id.elv_contact);
        mRlGroup = (RelativeLayout) findViewById(R.id.rl_group);
        mRcvContact = (RecyclerView) findViewById(R.id.lv_contact);
        mAdapter = new ContactAdapter(mContext);
        mRcvContact.setLayoutManager(new LinearLayoutManager(mContext));
        mRcvContact.setAdapter(mAdapter);
        mTvSearch = (TextView) findViewById(R.id.tv_search);
        mTvSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                startActivity(ImContactSearchActivity.class);
            }
        });
        mRlGroup.setOnClickListener(this);
    }

    private void initData() {
        mUser = app.getUser();
        contactList = mUser.getFriends();
        mAdapter.setData(contactList);
        mAdapter.notifyDataSetChanged();
        loadAllGroup();
    }

    private void loadAllGroup() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    final List<EMGroup> grouplist = EMClient.getInstance().groupManager().getJoinedGroupsFromServer();//需异步处理
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            mTvGroupNum.setText(grouplist.size() + "");
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }

            }
        }).start();
        DialogUtil.showLoadDiadlog(mContext);
        loadAllContact();
    }

    private void loadAllContact() {
        HashMap<String, String> params = new HashMap<>();
        params.put("token", mUser.getToken());
        mManager.post(NetworkAPI.FriendLIst, new HttpCallback() {
            @Override
            public void onSuccess(int code, String value, String msg) {
                DialogUtil.dismiss(mContext);
                if (code == 1) {
                    List<UserBean> list = GsonUtil.paraeFromStringToList(value, UserBean.class);
                    mUser.setFriends(list);
                    app.setUser(mUser);
                    spUtil.putString("user", GsonUtil.parseFromBeanToString(mUser));
                    for (int i = 0; i < list.size(); i++) {
                        spUtil.putObject(list.get(i).getEasemobNumber(), list.get(i));
                    }
                    loadData(list);
                } else {
                    ToastOpt.createToast(mContext, msg);
                }
            }

            @Override
            public void onFailure(String value) {
                ToastOpt.createToast(mContext, "请求失败");
                DialogUtil.dismiss(mContext);
            }
        }, params);
    }

    private void loadData(List<UserBean> list) {
        List<String> groups = new ArrayList<>();
        List<List<GroupContactBean>> childs = new ArrayList<>();
        List<GroupContactBean> childItem = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            UserBean easeUser = list.get(i);
            final DepInfo info = easeUser.getDept();
            if (info != null) {
                DepInfo preInfo = null;
                if (i > 0) {
                    preInfo = list.get(i - 1).getDept();
                }
                String preHead = "";
                if (preInfo != null) {
                    preHead = preInfo.getDeptName();
                }
                String header = info.getDeptName();
                if (i == 0 || TextUtils.isEmpty(preHead) || header != null && !header.equals(preHead)) {
                    if (!TextUtils.isEmpty(header)) {
                        groups.add(header);
                        if (i > 0) {
                            childs.add(childItem);
                        }
                        childItem = new ArrayList<>();
                    }
                }
                GroupContactBean bean = new GroupContactBean();
                bean.setBean(easeUser);
                bean.setSelect(false);
                childItem.add(bean);
            }
        }
        childs.add(childItem);
        ExpListAdapter adapter = new ExpListAdapter(mContext, groups, childs);
        mElvContact.setAdapter(adapter);
        mElvContact.setGroupIndicator(null);
        mElvContact.expandGroup(0);
        adapter.setOnItemClick(new OnItemOnclick<UserBean>() {
            @Override
            public void onClick(UserBean userBean, int position) {
                Intent intent = new Intent(mContext, ChatActivity.class);
                intent.putExtra("userId", userBean.getEasemobNumber());
                intent.putExtra("username", userBean.getUserName());
                mContext.startActivity(intent);
            }
        });
    }

    /***
     *
     */

    public List<UserBean> filter(String str) {
        List<UserBean> easeUsers = new ArrayList<>();
        for (int i = 0; i < contactList.size(); i++) {
            UserBean easeUser = contactList.get(i);
            if (easeUser.getUserName().contains(str)) {
                easeUsers.add(easeUser);
            }
        }

        return easeUsers;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_group:
                startActivity(ImGroupListActivity.class);
                break;
            default:
                break;
        }
    }
}
